﻿using GeneralDashboard.Data.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GeneralDashboard.Data.Adaptor
{
    public class FileStreamAsciiSplitProtocolAdaptor : AdaptorBase
    {
        private readonly Stream _input;
        private readonly Stream _output;
        private readonly MemoryStream _baseStream;

        private bool running = false;

        public FileStreamAsciiSplitProtocolAdaptor(string name, AsciiSplitProtocol protocol, FileInfo inputFile, FileInfo outputFile) : base(name)
        {
            if (!inputFile.Exists)
            {
                throw new FileNotFoundException("file not found.");
            }
            //outputFile.Create();
            _baseStream = new MemoryStream();
            
            _input = inputFile.OpenRead();
            _output = outputFile.OpenWrite();

            protocol.Initialise(_baseStream);
            Protocol = protocol;
        }

        public override void Close()
        {
            running = false;
        }

        public override void Open()
        {
            running = true;
            Task.Run(() =>
            {
                while (running)
                {
                    _input.CopyTo(_baseStream);
                    _baseStream.SetLength(_input.Length);
                    _baseStream.Seek(0, SeekOrigin.Begin);
                    Task.Delay(1000).Wait();
                }
            });
        }

        public override void Send(ReadOnlySpan<byte> data)
        {
            _output.Write(data);
            _output.Flush();
        }
    }
}
